
package com.xinan.weixin.menu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.BaseController;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SearchSql;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;
import com.xinan.utils.Constants;
import com.xinan.weixin.api.NewsApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WxMenuController extends BaseController {

    public void index() {
        render("/WEB-INF/views/weixin/menu/index.html");
    }

    /**
     * add
     */
    public void newModes() {
        String id = getPara("id");
        String pid = getPara("pid");
//    List<Record> newlist = Db.find("select  * from     where    id=  '" + id + "'");
        List<Record> newlist = WxMenu.dao.findAlls("       id=  '" + id + "'");

        setAttr("newlist", newlist);
        setAttr("pid", pid);
        setAttr("id", id);
        render("/WEB-INF/views/weixin/menu/wxMenu_form.html");

    }

    /**
     * 在增加了SearchSql拦截之后就可以根据页面配置信息
     * 自动装配查询语句放入request中,通过getAttr(Const.SEARCH_SQL)函数获得
     * 根据实际需要自动组装到Sql语句里面
     */
    @Before(SearchSql.class)
    public void query() {
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("rows");
        String where = getAttr(Const.SEARCH_SQL);
        Page<WxMenu> page = WxMenu.dao.page(pageNumber, pageSize, where);
    	Map root = new HashMap();
		// / jqgrid用 分页显示
		root.put("total", page.getTotalPage());
		root.put("page", page.getPageNumber());
		root.put("records", page.getTotalRow());
		root.put("rows", page.getList());
		renderJson(JsonKit.toJson(root));
    }


    public void getMenuTree() {
        String id = getPara("pid");
        String yxbz = getPara("yxbz");
        String where = "";
        if (StringKit.notBlank(yxbz)) {
            where += " where yxbz =" + yxbz + "  ";
        }
        List<Record> newlist = WxMenu.dao.findtree(where);
        JSONObject jo1 = new JSONObject();
        /// 增加根节点
        jo1.put("id", "0");
        jo1.put("pId", "0");
        jo1.put("name", "根节点");
        JSONArray jsonArr = new JSONArray();
        if (newlist.size() == 0) {
            jsonArr.add(jo1);
            renderJson(jsonArr);
        } else {
            for (int j = 0; j < newlist.size(); j++) {
                JSONObject jo = new JSONObject();
                jo.put("id", newlist.get(j).get("id"));
                jo.put("pId", newlist.get(j).get("pId"));
                jo.put("name", newlist.get(j).get("name"));
                jsonArr.add(jo);
            }
            jsonArr.add(jo1);
        }
        System.out.println(jsonArr);
        renderJson(jsonArr);

    }

    /**
     * save
     *
     * @param
     * @return
     */
    public void save() {
        if (getModel(WxMenu.class).save()) {
        	renderText(Constants.SAVESUCCESS);
        } else {
        	renderText(Constants.SAVEFAILED);
        }
    }

    /**
     * Post请求的菜单更新函数,可以接受菜单的id和菜单对象,并且根据菜单id进行更新,返回影响行数根据此判断是否操作成功
     * 本例子使用rose框架的est风格url可以吧参数作为路径一部分进行传递
     *
     * @param
     * @return
     */
    public void update() {
        if (getModel(WxMenu.class).update()) {
        	renderText(Constants.EDITSUCCESS);
        } else {
        	renderText(Constants.EDITFAILED);
        }
    }

    /**
     * Post请求的菜单删除函数,可以接受菜单ID 并且根据ID进行物理删除,并且返回影响行数,据此判断是否操作成功
     *
     * @param
     * @return
     */
    public void delete() {

        String where = " pid=  '" + getPara("id") + "'";
        List<Record> newlist = WxMenu.dao.findAlls(where);
        if (newlist.size() > 0) {
        	renderText("请删除子节点!");
        } else {
            if (WxMenu.dao.deleteById(getPara("id"))) {
            	renderText(Constants.DELETESUCCESS);
            } else {
            	renderText(Constants.DELETEFAILED);
            }
        }

    }


    /**
     * 创建自定义菜单
     */
    public void setMenu() {
        String menus = "{\"button\":[";
        String menua = "";
        MenuApi menuApi = new MenuApi();
        //ApiResult apiResult = menuApi.createMenu("{type: 'view',name: '点餐',url: 'http://loveyy.gnjsp.xzbiz.cn/_front/main.html/',sub_button: [ ]},{type: 'view',name: '我的订单',url: 'http://www.baidu.com',sub_button: [ ]},{type: 'view',name: '其他',url: 'http://www.baidu.com',sub_button: [ ]}]}}");
        List<Record> newlist = WxMenu.dao.findbymenu(" where level=1");
        List<Record> articleList = new ArrayList<Record>();
        Map articles = new HashMap();
        for (int i = 0; i < newlist.size(); i++) {
            Record article = new Record();
            String name = newlist.get(i).get("name");
            String id = newlist.get(i).get("id").toString();
            String type = newlist.get(i).get("type");
            String key = newlist.get(i).get("key");
            String url = newlist.get(i).get("url");
            String num = newlist.get(i).get("num").toString();
            if (!num.equals("0")) {
                List<Record> newlists = WxMenu.dao.findbymenu(" where level=2  and pid= '" + id + "'");
                List<Record> articleLista = new ArrayList<Record>();
                article.set("name", name);
                for (int j = 0; j < newlists.size(); j++) {
                    Record articlea = new Record();
                    String names = newlists.get(j).get("name");
                    String ids = newlists.get(j).get("id").toString();
                    String types = newlists.get(j).get("type");
                    String keys = newlists.get(j).get("key");
                    String urls = newlists.get(j).get("url");
                    String nums = newlists.get(j).get("num").toString();
                    articlea.set("name", names);
                    if (types.equals("click")) {
                        articlea.set("type", types);
                        articlea.set("key", keys);
                    } else if (types.equals("view")) {
                        articlea.set("type", types);
                        articlea.set("url", urls);
                    }
                    articleLista.add(articlea);
                    System.out.println("============" + articlea);
                }
                article.set("sub_button", articleLista);
            } else {
                article.set("name", name);
                if (type.equals("click")) {
                    article.set("type", type);
                    article.set("key", key);
                } else if (type.equals("view")) {
                    article.set("type", type);
                    article.set("url", url);
                }
            }
            articleList.add(article);
        }
        articles.put("button", articleList);
        String data = JsonKit.toJson(articles);

        ApiResult apiResult = menuApi.createMenu(data);

        System.out.println("======================" + AccessTokenApi.getAccessToken().getAccessToken());
        System.out.println("======================" + apiResult.getErrorCode());
        System.out.println("======================" + apiResult.getErrorMsg()
        );
        renderText(apiResult.getErrorMsg());
    }

}

